package com.molyfun.parents.activity.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.MainActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.LoginTIMUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.SinglineClearEditText;
import com.yilin.parents.wxapi.WXEntryActivity;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by liuchao on 7/12/16.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.activity_login_register)
    TextView mRegisterBtn;
    @InjectView(R.id.activity_login_forget_pwd)
    TextView mForgetPwd;
    @InjectView(R.id.login_login_btn)
    TextView mLoginBtn;
    @InjectView(R.id.activity_login_account)
    SinglineClearEditText mAccount;
    @InjectView(R.id.activity_login_pwd)
    SinglineClearEditText mPwd;
    @InjectView(R.id.thirdly_login)
    TextView mWX_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");

        mLoginBtn.setOnClickListener(this);
        mRegisterBtn.setOnClickListener(this);
        mForgetPwd.setOnClickListener(this);
        mWX_login.setOnClickListener(this);
        mAccount.setHint("请输入您的手机号码");
        mPwd.setHint("请输入您的密码");
        mPwd.setIsPwd();
        mAccount.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if(s.length() > 0){
                    if(!TextUtils.isEmpty(mPwd.getString())){
                        mLoginBtn.setEnabled(true);
                    }
                    if (s.length() > 11) {
                        toast("手机号长度超过11位");
                    }
                }else{
                    mLoginBtn.setEnabled(false);
                }
            }
        });

        mPwd.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    if(!TextUtils.isEmpty(mAccount.getString())){
                        mLoginBtn.setEnabled(true);
                    }
                }else{
                    mLoginBtn.setEnabled(false);
                }

                if (s.toString().contains(" ")) {
                    String[] str = s.toString().split(" ");
                    String str1 = "";
                    for (int i = 0; i < str.length; i++) {
                        str1 += str[i];
                    }
                    if (str1.equals("")) {
                        toast("密码不支持全部空格");
                    }
                }
            }
        });
    }

    private void showToast(String toast){
        Toast.makeText(LoginActivity.this, toast, Toast.LENGTH_SHORT);
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_login_register:
                mPwd.clear();
                Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
                LoginActivity.this.startActivity(registerIntent);
                break;
            case R.id.activity_login_forget_pwd:
                mPwd.clear();
                Intent forgetPwdIntent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                LoginActivity.this.startActivity(forgetPwdIntent);
                break;
            case R.id.login_login_btn:

                if (TextUtils.isEmpty(mAccount.getString())) {
                    toast("账号不能为空");
                    return;
                }
                if (mAccount.getString().trim().length() > 11) {
                    toast("手机号长度大于11位");
                    return;
                }
                if (TextUtils.isEmpty(mPwd.getString())) {
                    toast("密码不能为空");
                    return;
                }
                if (mAccount.getString().equals("111111")) {
                    if (mPwd.getString().equals("111111")) {
                        DebugModeActivity.startActivity(LoginActivity.this);
                        return;
                    }
                }
                login(mAccount.getString().trim(), mPwd.getString());
                break;
            case R.id.thirdly_login:
                //TODO 微信登录
                WXEntryActivity.loginWeixin(LoginActivity.this, MFPApplication.sApi);
            default:
                break;
        }
    }

    private void login(String phone, String pwd) {
        showProgressDialog();
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().login(phone, pwd);
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        MFPApplication.getInstance().setUser(response.body().getData());
                        if (response.body().getData() != null) {
                            PreferencesStorageUtil.setToken(LoginActivity.this, response.body().getData().getToken());
                            PreferencesStorageUtil.setUserBean(LoginActivity.this, GsonUtil.toJson(response.body().getData()));
                            PreferencesStorageUtil.setIMUserName(LoginActivity.this, response.body().getData().getImusername());
                            PreferencesStorageUtil.setIMUserPwd(LoginActivity.this, response.body().getData().getImpassword());
                            PreferencesStorageUtil.setPhoneNum(LoginActivity.this, response.body().getData().getPhone());
                            PreferencesStorageUtil.setAddress(LoginActivity.this, response.body().getData().getAddress());
                            PreferencesStorageUtil.setEmail(LoginActivity.this, response.body().getData().getEmail());
                            PreferencesStorageUtil.setStudentId(LoginActivity.this, response.body().getData().getStudentid());
                            if (TextUtils.isEmpty(response.body().getData().getStudentid())) {
                                PreferencesStorageUtil.setUserEnter(LoginActivity.this, false);
                            } else {
                                PreferencesStorageUtil.setUserEnter(LoginActivity.this, true);
                                PreferencesStorageUtil.setOriganOutShowSplash(MFPApplication.getInstance(), false);
                            }
                            MFPApplication.getInstance().refreshRestClient(response.body().getData().getToken());
                            PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());
                            LoginTIMUtil.getInstance().setLoginTime(System.currentTimeMillis());
                            Intent toMainIntent = new Intent(LoginActivity.this, MainActivity.class);
                            LoginActivity.this.startActivity(toMainIntent);
                            finish();
                        }
                    } else {
                        toast(response.body().getMsg());
                    }

                } else {
                    toast("登录失败");
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("登录失败");
            }
        });
    }

}
